<template>
  <div class="myContainer">
    <br/>
    <div class="sub-title">请输入翻译的网址</div>
    <br/>
    <el-autocomplete
      class="inline-input"
      v-model="state1"
      :fetch-suggestions="querySearch"
      placeholder="请输入翻译的网址"
      @select="handleSelect"
      style="width: 500px"
    >
      <template slot-scope="{ item }">
        <div class="name">{{ item.address }}</div>
        <span class="addr">{{ item.value }}</span>
      </template>
    </el-autocomplete>&nbsp;&nbsp;
    <el-button @click="submit" type="primary">翻译</el-button>
  </div>
</template>

<script>
export default {
  name: "index",
  data() {
    return {
      restaurants: [],
      state1: '',
    };
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.address.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    loadAll() {
      return [
        { "value": "https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#spring-core", "address": "Spring Framework Core" },
      ];
    },
    handleSelect(item) {
    },
    //键盘按键
    enterKey(event) {
      const componentName = this.$options.name;
      if (componentName == "index") {
        const code = event.keyCode
          ? event.keyCode
          : event.which
            ? event.which
            : event.charCode;
        if (code == 13) {
          this.submit();
        }
      }
    },
    enterKeyupDestroyed() {
      document.removeEventListener("keyup", this.enterKey);
    },
    enterKeyup() {
      document.addEventListener("keyup", this.enterKey);
    },
    //提交
    submit(){
      if(this.state1 != ""){
        this.$router.push({ path: "/english/translate", query: { translateUrl: this.state1}});
      }else{
        this.$modal.msg("请输入网址！");
      }
    }
  },
  mounted() {
    this.restaurants = this.loadAll();
    this.enterKeyup();
  },
  destroyed() {
    // 销毁enter事件
    this.enterKeyupDestroyed();
  },
}
</script>

<style scoped>
.addr {
  font-size: 12px;
  color: #b4b4b4;
}
.name {
  text-overflow: ellipsis;
  overflow: hidden;
}
.myContainer{
  text-align: center;
}
</style>
